package priv.pfz.basedao.lab.performance;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

import static org.junit.Assert.assertEquals;

/**
 * @author yyjxp
 * 2024/8/4 15:33
 */
public class ReflectMethod implements ReflectTest {
    private final List<Method> getters = Lists.newArrayList();

    public ReflectMethod() {
        try {
            Map<String, Method> getterMap = Maps.newHashMap();
            BeanInfo beanInfo = Introspector.getBeanInfo(TestBean.class);
            for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) {
                getterMap.put(pd.getName(), pd.getReadMethod());
            }
            for (Field field : TestBean.class.getDeclaredFields()) {
                getters.add(getterMap.get(field.getName()));
            }
        } catch (IntrospectionException e) {
            throw new RuntimeException(e);
        }
        assertEquals(10, getters.size());
    }

    @Override
    public String name() {
        return "反射调用getter";
    }

    @Override
    public void run(TestBean bean) {
        for (Method getter : getters) {
            try {
                getter.invoke(bean);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
